﻿using Abp.MultiTenancy;
using Abp.Runtime.Security;
using Abp.Runtime.Session;
using System;
using System.Linq;
using System.Security.Claims;

namespace Hicap.QRCodeWarehouse.Core.Common
{
    /// <summary>
    /// Get session from principal, instead of default abpSession
    /// </summary>
    public partial class HicapSession : IAbpSession
    {
        private const int DefaultTenantId = 1;
        protected IPrincipalAccessor PrincipalAccessor { get; }

        public MultiTenancySides MultiTenancySide { get; }

        public IDisposable Use(int? tenantId, long? userId)
        {
            throw new NotImplementedException();
        }

        public long? UserId
        {
            get
            {
                ClaimsPrincipal principal = PrincipalAccessor.Principal;

                Claim claim = principal?.Claims.FirstOrDefault(c => c.Type == AbpClaimTypes.UserId);

                if (!string.IsNullOrEmpty(claim?.Value))
                    return new int?(Convert.ToInt32(claim.Value));

                return new int?();
            }
        }

        public int? TenantId => DefaultTenantId;

        public long? ImpersonatorUserId => null;

        public int? ImpersonatorTenantId => DefaultTenantId;

        /// <summary>
        /// Constructor.
        /// </summary>
        public HicapSession(IPrincipalAccessor principalAccessor)
        {
            PrincipalAccessor = principalAccessor;
        }
    }
}